package com.zhouliang.jwt;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.sun.org.apache.xml.internal.security.algorithms.SignatureAlgorithm;
import com.zhouliang.error.DouyinException;
import com.zhouliang.error.StatusCode;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtUtil {
    private static final String salt = "zhou_liang";

    /**
     *
     * @param userId 用户id
     * @param userName 用户名
     * @return 返回用户id和用户名加密生成的token
     */
    public static String generateToken(Long userId, String userName) {
        JWTCreator.Builder builder = JWT.create();
        Map<String, Object> header = new HashMap<>();
        header.put("typ", "jwt");
        header.put("alg", "HS256");
        return builder.withHeader(header)
                .withClaim("userId", userId)
                .withClaim("userName", userName)
                //.withExpiresAt(new Date(System.currentTimeMillis() + 1000 * 60 * 60)) 过期时间放到redis中方便处理。
                .sign(Algorithm.HMAC256(salt));
    }

    /**
     *
     * @param token 加密token
     * @return 解析token返回TokenDto对象
     */
    public static TokenDto parseToken(String token){
        DecodedJWT decode = JWT.decode(token);
        Map<String, Claim> claims = decode.getClaims();
        return new TokenDto(claims.get("userId").asLong(), claims.get("userName").asString());
    }

    static class TokenDto {
        private Long id;
        private String name;

        public TokenDto(Long id, String name) {
            this.id = id;
            this.name = name;
        }

        public String getName() {
            return name;
        }

        public Long getId() {
            return id;
        }

        @Override
        public String toString() {
            return "TokenDto{" +
                    "id=" + id +
                    ", name='" + name + '\'' +
                    '}';
        }
    }
}
